<?php

/**
 * SocialEngine
 *
 * @category   Application_Extensions
 * @package    Sitepage
 * @copyright  Copyright 2010-2011 BigStep Technologies Pvt. Ltd.
 * @license    http://www.socialengineaddons.com/license/
 * @version    $Id: Core.php 2011-05-05 9:40:21Z SocialEngineAddOns $
 * @author     SocialEngineAddOns
 */
class Sitepage_Api_Core extends Core_Api_Abstract {
  /**
   * Privacy settings base on level and package
   *
   * @param object $sitepage
   * @param string $privacy_type
   * @return int $is_manage_admin
   */
  public function isManageAdmin($sitepage, $privacy_type) {
    $page_id = $sitepage->page_id;
    //page is declined then not edit page
    if (!empty($sitepage->declined) && ($privacy_type == "edit")) {
      return 0;
    }

    if ($privacy_type == "view" && !$this->canViewPage($sitepage)) {
      return 0;
    }

    if ($this->hasPackageEnable()) {

      $packageInclude = array("tellafriend" => "tfriend", "print" => "print", "overview" => "overview", "map" => "map", "insights" => "insight", /* "layout" => "layout", */ "contact_details" => "contact", "profile" => "profile", "foursquare" => "foursquare", "sendupdate" => "sendupdate");
      $packageOwnerModules = array("sitepageoffer" => "offer", "sitepageform" => "form", "sitepageinvite" => "invite", "sitepagebadge" => "badge", "sitepagelikebox" => "likebox");
      $subModules = array("sitepagedocument" => "sdcreate", "sitepagenote" => "sncreate", "sitepagepoll" => "splcreate", "sitepageevent" => "secreate", "sitepagevideo" => "svcreate", "sitepagealbum" => "spcreate", "sitepagemusic" => "smcreate");

      $packageSubModule = $this->getEnableSubModules();

      //non sub modules
      $search_Key = array_search($privacy_type, $packageInclude);
      if (!empty($search_Key)) {
        return $this->allowPackageContent($sitepage->package_id, $search_Key);
      }

      //owner base submodules
      $packageOwnerSubModule = @array_search($privacy_type, $packageOwnerModules);
      if (!empty($packageOwnerSubModule)) {
        return $this->allowPackageContent($sitepage->package_id, "modules", $packageOwnerSubModule);
      }

      //owner base and also depeanded on viewer
      $subModule = @array_search($privacy_type, $subModules);

      if (!empty($subModule)) {
        if (!$this->allowPackageContent($sitepage->package_id, "modules", $subModule))
          return 0;
      }
    }else {

      $levelInclude = array("tellafriend" => "tfriend", "print" => "print", "overview" => "overview", "map" => "map", "insights" => "insight", /* "layout" => "layout", */ "contact_details" => "contact", "profile" => "profile", "foursquare" => "foursquare", "sendupdate" => "sendupdate");
      $levelOwnerModules = array("sitepageoffer" => "offer", "sitepageform" => "form", "sitepageinvite" => "invite", "sitepagebadge" => "badge", "sitepagelikebox" => "likebox");
      $levelPageBaseSubModule = array("sitepagedocument" => "sdcreate", "sitepagenote" => "sncreate", "sitepagepoll" => "splcreate", "sitepageevent" => "secreate", "sitepagevideo" => "svcreate", "sitepagealbum" => "spcreate", "sitepagemusic" => "smcreate");
      //non sub modules
      $search_Key = array_search($privacy_type, $levelInclude);
      if (!empty($search_Key)) {
        $page_owner = Engine_Api::_()->getItem('user', $sitepage->owner_id);
        $can_edit = Engine_Api::_()->authorization()->getPermission($page_owner->level_id, 'sitepage_page', $privacy_type); //Engine_Api::_()->authorization()->isAllowed($sitepage, $page_owner, $privacy_type);
        if (empty($can_edit)) {
          return 0;
        } else {
          return 1;
        }
      }

      //owner base submodules
      $levelsubModule = @array_search($privacy_type, $levelOwnerModules);
      if (!empty($levelsubModule)) {
        $page_owner = Engine_Api::_()->getItem('user', $sitepage->owner_id);
        $can_edit = Engine_Api::_()->authorization()->getPermission($page_owner->level_id, 'sitepage_page', $privacy_type);
        if (empty($can_edit)) {
          return 0;
        } else {
          return 1;
        }
      }

      //owner base and also depeanded on viewer
      $levelsubModule = @array_search($privacy_type, $levelPageBaseSubModule);
      if (!empty($levelsubModule)) {
        $page_owner = Engine_Api::_()->getItem('user', $sitepage->owner_id);
        $can_edit = Engine_Api::_()->authorization()->getPermission($page_owner->level_id, 'sitepage_page', $privacy_type);
        if (empty($can_edit)) {
          return 0;
        }
      }
    }
    $existManageAdmin = 0;
    $viewer = Engine_Api::_()->user()->getViewer();
    $viewer_id = $viewer->getIdentity();
    $manageAdminEnable = Engine_Api::_()->getApi('settings', 'core')->getSetting('sitepage.manageadmin', 1);
    if (!empty($manageAdminEnable)) {
      $manageadminTable = Engine_Api::_()->getDbtable('manageadmins', 'sitepage');
      $manageadminTableName = $manageadminTable->info('name');
      $select = $manageadminTable->select()
                      ->from($manageadminTableName, 'manageadmin_id')
                      ->where('user_id = ?', $viewer_id)
                      ->where('page_id = ?', $page_id)
                      ->limit(1);
      $row = $manageadminTable->fetchAll($select)->toArray();
      if (!empty($row[0]['manageadmin_id'])) {
        $existManageAdmin = 1;
      } else {
        $existManageAdmin = 0;
      }
    }
    $is_manage_admin = 1;

    if ($existManageAdmin == 0 || $viewer_id == $sitepage->owner_id) {
      $can_edit = Engine_Api::_()->authorization()->isAllowed($sitepage, $viewer, $privacy_type);
      if (empty($can_edit)) {
        $is_manage_admin = 0;
      }
    } elseif ($existManageAdmin == 1 && $viewer_id != $sitepage->owner_id) {
      $page_owner = Engine_Api::_()->getItem('user', $sitepage->owner_id);
      $can_edit = Engine_Api::_()->authorization()->isAllowed($sitepage, $page_owner, $privacy_type);
      if (empty($can_edit)) {
        $is_manage_admin = 0;
      }
    }

    return $is_manage_admin;
  }

  /**
   * viewer is page owner or page admin
   *
   * @param object $sitepage
   * @return bool $isPageOwnerFlage
   */
  public function isPageOwner($sitepage) {

    $viewer_id = Engine_Api::_()->user()->getViewer()->getIdentity();
    $isPageOwnerFlage = false;
    if (empty($viewer_id))
      return $isPageOwnerFlage;
    if ($sitepage->owner_id == $viewer_id)
      return true;

    $manageadminTable = Engine_Api::_()->getDbtable('manageadmins', 'sitepage');
    $manageadminTableName = $manageadminTable->info('name');
    $select = $manageadminTable->select()
                    ->from($manageadminTableName, 'manageadmin_id')
                    ->where('user_id = ?', $viewer_id)
                    ->where('page_id = ?', $sitepage->page_id);
    $row = $manageadminTable->fetchRow($select);
    if (!empty($row))
      $isPageOwnerFlage = true;

    return $isPageOwnerFlage;
  }

  /**
   * allow to page owner
   *
   * @param object $sitepage
   * @param string $privacy_type
   * @return bool $canDo
   */
  public function isPageOwnerAllow($sitepage, $privacy_type) {
    $page_owner = Engine_Api::_()->getItem('user', $sitepage->owner_id);
    return (bool) $canDo = Engine_Api::_()->authorization()->getPermission($page_owner->level_id, 'sitepage_page', $privacy_type);
  }

  public function setDisabledType() {
    $modArray = unserialize(Engine_Api::_()->getApi('settings', 'core')->getSetting('sitepage.mod.settings', 0));
    $modArrayType = unserialize(Engine_Api::_()->getApi('settings', 'core')->getSetting('sitepage.mod.types', 0));
    if (!empty($modArray)) {
      foreach ($modArray as $modName) {
        $newModArray[] = strrev($modName);
      }
      Engine_Api::_()->getApi('settings', 'core')->setSetting('sitepage.mod.settings', serialize($newModArray));
    }
    if (!empty($modArrayType)) {
      foreach ($modArrayType as $modNameType) {
        $newModArrayType[] = strrev($modNameType);
      }
      Engine_Api::_()->getApi('settings', 'core')->setSetting('sitepage.mod.types', serialize($newModArrayType));
    }
  }

  /**
   * Get page id
   *
   * @param string $page_url
   * @return int $pageID
   */
  public function getPageId($page_url) {
    $pageID = 0;
    if (!empty($page_url)) {
      $sitepage_table = Engine_Api::_()->getItemTable('sitepage_page');
      $page = $sitepage_table->fetchRow(array('page_url = ?' => $page_url));
      if (!empty($page))
        $pageID = $page->page_id;
    }

    return $pageID;
  }

  /**
   * Get page url
   *
   * @param int $page_id
   * @return string $pageUrl
   */
  public function getPageUrl($page_id) {

    $pageUrl = 0;
    if (!empty($page_id)) {
      $sitepage_table = Engine_Api::_()->getItemTable('sitepage_page');
      $page = $sitepage_table->fetchRow(array('page_id = ?' => $page_id));
      if (!empty($page))
        $pageUrl = $page->page_url;
    }
    return $pageUrl;
  }

  /**
   * Get page list
   *
   * @param array $params
   * @param array $customParams
   * @return array $paginator;
   */
  public function getSitepagesPaginator($params = array(), $customParams = null) {

    $paginator = Zend_Paginator::factory($this->getSitepagesSelect($params, $customParams));
    if (!empty($params['page'])) {
      $paginator->setCurrentPageNumber($params['page']);
    }

    if (!empty($params['limit'])) {
      $paginator->setItemCountPerPage($params['limit']);
    }

    return $paginator;
  }

  /**
   * Get page select query
   *
   * @param array $params
   * @param array $customParams
   * @return string $select;
   */
  public function getSitepagesSelect($params = array(), $customParams = null) {

    $table = Engine_Api::_()->getDbtable('pages', 'sitepage');
    $rName = $table->info('name');

    $tmTable = Engine_Api::_()->getDbtable('TagMaps', 'core');
    $tmName = $tmTable->info('name');

    $searchTable = Engine_Api::_()->fields()->getTable('sitepage_page', 'search')->info('name');

    $locationTable = Engine_Api::_()->getDbtable('locations', 'sitepage');
    $locationName = $locationTable->info('name');
    $select = $table->select();
    if (!empty($params['type']) && empty($params['orderby'])) {
      if ($params['type'] == 'browse') {
        $order = Engine_Api::_()->getApi('settings', 'core')->getSetting('sitepage.browseorder', 1);
        switch ($order) {
          case "1":
            $select->order($rName . '.creation_date DESC');
            break;
          case "2":
            $select->order($rName . '.view_count DESC');
            break;
          case "3":
            $select->order($rName . '.title');
            break;
          case "4":
            $select->order($rName . '.sponsored' . ' DESC');
            break;
          case "5":
            $select->order($rName . '.featured' . ' DESC');
            break;
          case "6":
            $select->order($rName . '.sponsored' . ' DESC');
            $select->order($rName . '.featured' . ' DESC');
            break;
          case "7":
            $select->order($rName . '.featured' . ' DESC');
            $select->order($rName . '.sponsored' . ' DESC');
            break;
        }
      }
    } else {
      if (!empty($params['orderby']) && $params['orderby'] == "title") {
        $select->order($rName . '.' . $params['orderby']);
      } elseif (isset($params['orderby']))
        $select->order($rName . '.' . $params['orderby'] . ' DESC');
    }
    $select->order($rName . '.creation_date DESC');
    $select = $select
                    ->setIntegrityCheck(false)
                    ->from($rName);

    if (isset($params['type'])&& !empty($params['type']) && $params['type'] != 'manage') {
      if ($params['type'] == 'browse' || $params['type'] == 'home') {
        $select = $select
                        ->where($rName . '.approved = ?', '1')
                        ->where($rName . '.declined = ?', '0')
                        ->where($rName . '.draft = ?', '1');
        $stusShow = Engine_Api::_()->getApi('settings', 'core')->getSetting('sitepage.status.show', 1);
        if ($stusShow == 0) {
          $select = $select
                          ->where($rName . '.closed = ?', '0');
        }
        if ($this->hasPackageEnable())
          $select->where($rName . '.expiration_date  > ?', date("Y-m-d H:i:s"));
      } elseif ($params['type'] == 'browse_home_zero') {
        $select = $select
                        ->where($rName . '.closed = ?', '0')
                        ->where($rName . '.approved = ?', '1')
                        ->where($rName . '.declined = ?', '0')
                        ->where($rName . '.draft = ?', '1');
        if ($this->hasPackageEnable())
          $select->where($rName . '.expiration_date  > ?', date("Y-m-d H:i:s"));
      }
      $select->where($rName . ".search = ?", 1);
    }
    if (isset($customParams)) {
      $select = $select
                      ->setIntegrityCheck(false)
                      ->joinLeft($searchTable, "$searchTable.item_id = $rName.page_id", null);

      $searchParts = Engine_Api::_()->fields()->getSearchQuery('sitepage_page', $customParams);
      foreach ($searchParts as $k => $v) {
        $select->where("`{$searchTable}`.{$k}", $v);
      }
    }

    if (isset($params['sitepage_price']) && !empty($params['sitepage_price'])) {

      if ((!empty($params['sitepage_price']['min']) && !empty($params['sitepage_price']['max']))) {

        if ($params['sitepage_price']['max'] < $params['sitepage_price']['min']) {
          $min = $params['sitepage_price']['max'];
          $max = $params['sitepage_price']['min'];
        } else {
          $min = $params['sitepage_price']['min'];
          $max = $params['sitepage_price']['max'];
        }

        $select = $select->where($rName . '.price >= ?', $min)->where($rName . '.price <= ?', $max);
      }

      if ((empty($params['sitepage_price']['min']) && !empty($params['sitepage_price']['max']))) {
        $select = $select->where($rName . '.price <= ?', $params['sitepage_price']['max']);
      }

      if ((!empty($params['sitepage_price']['min']) && empty($param['sitepage_price']['max']))) {
        $select = $select->where($rName . '.price >= ?', $params['sitepage_price']['min']);
      }
    }

    if (isset($params['sitepage_location']) && !empty($params['sitepage_location'])) {
      $enable = Engine_Api::_()->getApi('settings', 'core')->getSetting('sitepage.proximitysearch', 1);
      if (isset($params['locationmiles']) && (!empty($params['locationmiles']) && !empty($enable))) {
        $longitude = 0;
        $latitude = 0;
        $selectLocQuery = $locationTable->select()->where('location = ?', $params['sitepage_location']);
        $locationValue = $locationTable->fetchRow($selectLocQuery);
        $enableSocialengineaddon = Engine_Api::_()->getDbtable('modules', 'core')->isModuleEnabled('socialengineaddon');

        if (empty($locationValue)) {
          $getSEALocation = array();
          if (!empty($enableSocialengineaddon)) {
            $getSEALocation = Engine_Api::_()->getDbtable('locations', 'socialengineaddon')->getLocation(array('location' => $params['sitepage_location']));
          }
          if (empty($getSEALocation)) {
            //   $locationLocal =  $params['sitepage_location'];
            $urladdress = str_replace(" ", "+", $params['sitepage_location']);
            //Initialize delay in geocode speed
            $delay = 0;
            //Iterate through the rows, geocoding each address
            $geocode_pending = true;
            while ($geocode_pending) {
              $request_url = "http://maps.googleapis.com/maps/api/geocode/json?address=$urladdress&sensor=true";

              $ch = @curl_init();
              $timeout = 0;
              curl_setopt($ch, CURLOPT_URL, $request_url);
              curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
              ob_start();
              curl_exec($ch);
              curl_close($ch);
              $json_resopnse = Zend_Json::decode(ob_get_contents());
              ob_end_clean();
              $status = $json_resopnse['status'];
              if (strcmp($status, "OK") == 0) {
                //Successful geocode
                $geocode_pending = false;
                $result = $json_resopnse['results'];

                //Format: Longitude, Latitude, Altitude
                $latitude = (float) $result[0]['geometry']['location']['lat'];
                $longitude = (float) $result[0]['geometry']['location']['lng'];
              }
            }
          } else {
            $latitude = (float) $getSEALocation->latitude;
            $longitude = (float) $getSEALocation->longitude;
          }
        } else {
          $latitude = (float) $locationValue->latitude;
          $longitude = (float) $locationValue->longitude;
        }

        $radius = $params['locationmiles']; //in miles

        $flage = Engine_Api::_()->getApi('settings', 'core')->getSetting('sitepage.proximity.search.kilometer', 0);
        if (!empty($flage)) {
          $radius = $radius * (0.621371192);
        }
        $latitudeRadians = deg2rad($latitude);
        $latitudeSin = sin($latitudeRadians);
        $latitudeCos = cos($latitudeRadians);
        $select->join($locationName, "$rName.page_id = $locationName.page_id   ", null);
        $sqlstring = "((degrees(acos($latitudeSin * sin(radians($locationName.latitude)) + $latitudeCos * cos(radians($locationName.latitude)) * cos(radians($longitude - $locationName.longitude)))) * 69.172 <= " . "'" . $radius . "'";
        $sqlstring .= ") OR (" . $locationName . ".latitude = '" . $latitude . "' AND  " . $locationName . ".longitude= '" . $longitude . "'))";
        $select->where($sqlstring);
      } else {
        $select->join($locationName, "$rName.page_id = $locationName.page_id", null);
        $select->where("`{$locationName}`.location LIKE ? or `{$locationName}`.city LIKE ? or `{$locationName}`.state LIKE ?", "%" . $params['sitepage_location'] . "%");
      }
    } elseif ((int) Engine_Api::_()->getDbtable('modules', 'core')->isModuleEnabled('sitepagegeolocation') && isset($params['has_currentlocation']) && !empty($params['has_currentlocation']) && !empty($params['latitude']) && !empty($params['longitude'])) {
      $radius = Engine_Api::_()->getApi('settings', 'core')->getSetting('sgl.geolocation.range', 100); // in miles
      $latitude = $params['latitude'];
      $longitude = $params['longitude'];
      $flage = Engine_Api::_()->getApi('settings', 'core')->getSetting('sitepage.proximity.search.kilometer', 0);
      if (!empty($flage)) {
        $radius = $radius * (0.621371192);
      }
      $latitudeRadians = deg2rad($latitude);
      $latitudeSin = sin($latitudeRadians);
      $latitudeCos = cos($latitudeRadians);
      $select->join($locationName, "$rName.page_id = $locationName.page_id   ", null);
      $sqlstring = "((degrees(acos($latitudeSin * sin(radians($locationName.latitude)) + $latitudeCos * cos(radians($locationName.latitude)) * cos(radians($longitude - $locationName.longitude)))) * 69.172 <= " . "'" . $radius . "'";
      $sqlstring .= ") OR (" . $locationName . ".latitude = '" . $latitude . "' AND  " . $locationName . ".longitude= '" . $longitude . "'))";
      $select->where($sqlstring);
    }
    //Start Network work
    if (!empty($params['type'])) {
      if ($params['type'] == 'browse' || $params['type'] == 'home' || $params['type'] == 'browse_home_zero') {

        $enableNetwork = Engine_Api::_()->getApi('settings', 'core')->getSetting('sitepage.network', 0);
        if (!empty($enableNetwork) || (isset($params['show']) && $params['show'] == "3")) {

          $viewer = Engine_Api::_()->user()->getViewer();
          $networkMembershipTable = Engine_Api::_()->getDbtable('membership', 'network');

          if (!Engine_Api::_()->getApi('subCore', 'sitepage')->pageBaseNetworkEnable()) {
            $viewerNetwork = $networkMembershipTable->fetchRow(array('user_id = ?' => $viewer->getIdentity()));
            if (!empty($viewerNetwork)) {
              $networkMembershipName = $networkMembershipTable->info('name');
              $select
                      ->join($networkMembershipName, "`{$rName}`.owner_id = `{$networkMembershipName}`.user_id  ", null)
                      ->join($networkMembershipName, "`{$networkMembershipName}`.`resource_id`=`{$networkMembershipName}_2`.resource_id", null)
                      ->where("`{$networkMembershipName}_2`.user_id = ? ", $viewer->getIdentity())
              ;
            }
          } else {
            $viewerNetwork = $networkMembershipTable->getMembershipsOfInfo($viewer);
            $str = array();
            $columnName = "`{$rName}`.networks_privacy";
            foreach ($viewerNetwork as $networkvalue) {
              $network_id = $networkvalue->resource_id;
              $str[] = "'" . $network_id . "'";
              $str[] = "'" . $network_id . ",%'";
              $str[] = "'%," . $network_id . ",%'";
              $str[] = "'%," . $network_id . "'";
            }
            if (!empty($str)) {
              $likeNetworkVale = (string) ( join(" or $columnName  LIKE ", $str) );
              $select->where($columnName . ' LIKE ' . $likeNetworkVale . ' or ' . $columnName . " IS NULL");
            } else {
              $select->where($columnName . " IS NULL");
            }
          }
        }
      }
    }
    //End Network work
    if (!empty($params['user_id']) && is_numeric($params['user_id'])) {
      $select->where($rName . '.owner_id = ?', $params['user_id']);
    }

    if (!empty($params['user']) && $params['user'] instanceof User_Model_User) {
      $select->where($rName . '.owner_id = ?', $params['user']->getIdentity());
    }

    if (!empty($params['users'])) {
      $str = (string) ( is_array($params['users']) ? "'" . join("', '", $params['users']) . "'" : $params['users'] );
      $select->where($rName . '.owner_id in (?)', new Zend_Db_Expr($str));
    }

    if (empty($params['users']) && isset($params['show']) && $params['show'] == '2') {
      $select->where($rName . '.owner_id = ?', '0');
    }
    if (!empty($params['tag'])) {
      $select
              ->setIntegrityCheck(false)
              ->joinLeft($tmName, "$tmName.resource_id = $rName.page_id")
              ->where($tmName . '.resource_type = ?', 'sitepage_page')
              ->where($tmName . '.tag_id = ?', $params['tag']);
    }

    if (isset($params['adminpages'])) {
      $str = (string) ( is_array($params['adminpages']) ? "'" . join("', '", $params['adminpages']) . "'" : $params['adminpages'] );
      $select->where($rName . '.page_id in (?)', new Zend_Db_Expr($str));
    }

    if (!empty($params['category'])) {
      $select->where($rName . '.category_id = ?', $params['category']);
    }

    if (!empty($params['category_id'])) {
      $select->where($rName . '.category_id = ?', $params['category_id']);
    }
    
    if ((int) Engine_Api::_()->getDbtable('modules', 'core')->isModuleEnabled('sitepagebadge') && Engine_Api::_()->getApi('settings', 'core')->getSetting('sitepagebadge.seaching.bybadge', 1)) {
      if (!empty($params['badge_id'])) {
        $select->where($rName . '.badge_id = ?', $params['badge_id']);
      }
    }

    if (!empty($params['profile_type'])) {
      $select->where($rName . '.profile_type = ?', $params['profile_type']);
    }

    if (!empty($params['subcategory'])) {
      $select->where($rName . '.subcategory_id = ?', $params['subcategory']);
    }

    if (!empty($params['subcategory_id'])) {
      $select->where($rName . '.subcategory_id = ?', $params['subcategory_id']);
    }

    if (!empty($params['subsubcategory'])) {
      $select->where($rName . '.subsubcategory_id = ?', $params['subsubcategory']);
    }

    if (!empty($params['subsubcategory_id'])) {
      $select->where($rName . '.subsubcategory_id = ?', $params['subsubcategory_id']);
    }
    
    if (isset($params['closed']) && $params['closed'] != "") {
      $select->where($rName . '.closed = ?', $params['closed']);
    }

    //Could we use the search indexer for this?
    if (!empty($params['search'])) {

      $tagName = Engine_Api::_()->getDbtable('Tags', 'core')->info('name');
      $select
              ->setIntegrityCheck(false)
              ->joinLeft($tmName, "$tmName.resource_id = $rName.page_id and " . $tmName . ".resource_type = 'sitepage_page'")
              ->joinLeft($tagName, "$tagName.tag_id = $tmName.tag_id");

      $select->where($rName . ".title LIKE ? OR " . $rName . ".body LIKE ? OR " . $tagName . ".text LIKE ? ", '%' . $params['search'] . '%');
    }

    if (!empty($params['start_date'])) {
      $select->where($rName . ".creation_date > ?", date('Y-m-d', $params['start_date']));
    }

    if (!empty($params['end_date'])) {
      $select->where($rName . ".creation_date < ?", date('Y-m-d', $params['end_date']));
    }

    if (!empty($params['has_photo'])) {
      $select->where($rName . ".photo_id > ?", 0);
    }

    if (!empty($params['has_review'])) {
      $select->where($rName . ".review_count > ?", 0);
    }

    if ((isset($_GET['alphabeticsearch']) && $_GET['alphabeticsearch'] != 'all' && $_GET['alphabeticsearch'] != '@')) {
      $select->where($rName . ".title LIKE ?", $_GET['alphabeticsearch'] . '%');
    } elseif (isset($_GET['alphabeticsearch']) && ($_GET['alphabeticsearch'] == 'all' && $_GET['alphabeticsearch'] != '@')) {
      $select->group($rName . '.page_id');
      return $select;
    } elseif (isset($_GET['alphabeticsearch']) && ($_GET['alphabeticsearch'] == '@' && $_GET['alphabeticsearch'] != 'all')) {
      $select->where($rName . ".title REGEXP '^[0-9]'");
    }

    $select->group($rName . '.page_id');

    return $select;
  }

  public function getPackageAuthInfo($modulename) {
    $sitepageModSetting = Engine_Api::_()->getApi('settings', 'core')->getSetting('sitepage.mod.settings', 0);
    $sitepageModType = Engine_Api::_()->getApi('settings', 'core')->getSetting('sitepage.mod.types', 0);
    $modSecondArray = $modFirstArray = array();
    if (!empty($sitepageModSetting)) {
      $modFirstArray = unserialize($sitepageModSetting);
    }
    if (!empty($sitepageModType)) {
      $modSecondArray = unserialize($sitepageModType);
    }
    $modArray = array_merge($modFirstArray, $modSecondArray);
    return in_array(strrev($modulename), $modArray);
  }

  /**
   * Get Page View Link
   *
   * @param int $page_id
   * @param int $owner_id
   * @param string $slug
   * @return link
   */
  public function getHref($page_id, $owner_id, $slug =null) {

    $page_url = Engine_Api::_()->sitepage()->getPageUrl($page_id);
    $params = array_merge(array('page_url' => $page_url));
    return Zend_Controller_Front::getInstance()->getRouter()
            ->assemble($params, 'sitepage_entry_view', true);
  }

  public function sitepage_auth($admin_tab) {
    include_once APPLICATION_PATH . '/application/modules/Sitepage/controllers/license/license2.php';
    return $checkAuth;
  }

//

  /**
   * GET LINK OF PHOTO VIEW PAGE
   *
   * @param object $image
   * @param array $params
   * @return link
   */
  public function getHreflink($image, $params = array()) {
    $params = array_merge(array(
                'route' => 'sitepage_imagephoto_specific',
                'reset' => true,
                'controller' => 'photo',
                'action' => 'view',
                'photo_id' => $image->getIdentity(),
                'album_id' => $image->collection_id,
                    ), $params);
    $route = $params['route'];
    $reset = $params['reset'];
    unset($params['route']);
    unset($params['reset']);
    return Zend_Controller_Front::getInstance()->getRouter()
            ->assemble($params, $route, $reset);
  }

  /**
   * Get Pages listing according to requerment
   *
   * @param string $sitepagetype
   * @param array $params
   * @return objects
   */
  public function getLising($sitepagetype, $params =array()) {

    $limit = 10;
    $table = Engine_Api::_()->getDbtable('pages', 'sitepage');
    $rName = $table->info('name');
    $coreTable = Engine_Api::_()->getDbtable('likes', 'core');
    $coreName = $coreTable->info('name');
    $select = $table->select()
                    ->where($rName . '.closed = ?', '0')
                    ->where($rName . '.approved = ?', '1')
                    ->where($rName . '.declined = ?', '0')
                    ->where($rName . '.draft = ?', '1');
    $select->where($rName . ".search = ?", 1);
    if ($this->hasPackageEnable())
      $select->where($rName . '.expiration_date  > ?', date("Y-m-d H:i:s"));

    //Start Network work
    $enableNetwork = Engine_Api::_()->getApi('settings', 'core')->getSetting('sitepage.network', 0);
    if (!empty($enableNetwork)) {
      $viewer = Engine_Api::_()->user()->getViewer();
      $networkMembershipTable = Engine_Api::_()->getDbtable('membership', 'network');
      if (!Engine_Api::_()->getApi('subCore', 'sitepage')->pageBaseNetworkEnable()) {
        $viewerNetwork = $networkMembershipTable->fetchRow(array('user_id = ?' => $viewer->getIdentity()));
        if (!empty($viewerNetwork)) {
          $select->setIntegrityCheck(false)
                  ->from($rName);
          $networkMembershipName = $networkMembershipTable->info('name');
          $select
                  ->join($networkMembershipName, "`{$rName}`.owner_id = `{$networkMembershipName}`.user_id  ", null)
                  ->join($networkMembershipName, "`{$networkMembershipName}`.`resource_id`=`{$networkMembershipName}_2`.resource_id", null)
                  ->where("`{$networkMembershipName}_2`.user_id = ? ", $viewer->getIdentity())
                  ->group($rName . ".page_id")
          ;
        }
      } else {
        $viewerNetwork = $networkMembershipTable->getMembershipsOfInfo($viewer);
        $str = array();
        $columnName = "`{$rName}`.networks_privacy";
        foreach ($viewerNetwork as $networkvalue) {
          $network_id = $networkvalue->resource_id;
          $str[] = "'" . $network_id . "'";
          $str[] = "'" . $network_id . ",%'";
          $str[] = "'%," . $network_id . ",%'";
          $str[] = "'%," . $network_id . "'";
        }
        if (!empty($str)) {
          $likeNetworkVale = (string) ( join(" or $columnName  LIKE ", $str) );
          $select->where($columnName . ' LIKE ' . $likeNetworkVale . ' or ' . $columnName . " IS NULL");
        } else {
          $select->where($columnName . " IS NULL");
        }
      }
    }
    //End Network work
    if ($sitepagetype == 'Most Viewed') {
      $select = $select->where($rName . '.view_count <> ?', '0')->order($rName . '.view_count DESC');
      $ShowViewArray = Engine_Api::_()->getApi('settings', 'core')->getSetting('sitepage.ajax.widgets.layout', array("0" => "1", "1" => "2", "2" => "3"));
      $limit = 0;
      $temp_limit = 0;
      if (in_array("2", $ShowViewArray))
        $limit = (int) Engine_Api::_()->getApi('settings', 'core')->getSetting('sitepage.popular.thums', 15);
      if (in_array("1", $ShowViewArray))
        $temp_limit = (int) Engine_Api::_()->getApi('settings', 'core')->getSetting('sitepage.popular.widgets', 10);

      if ($limit < $temp_limit) {
        $limit = $temp_limit;
      }
    }

    if ($sitepagetype == 'Most Viewed List') {
      $select = $select->where($rName . '.view_count <> ?', '0')->order($rName . '.view_count DESC');
      $limit = (int) Engine_Api::_()->getApi('settings', 'core')->getSetting('sitepage.popular.widgets', 10);
    }

    if ($sitepagetype == 'Recently Posted List') {
      $select = $select->order($rName . '.creation_date DESC');
      $limit = (int) Engine_Api::_()->getApi('settings', 'core')->getSetting('sitepage.recent.widgets', 10);
    }

    if ($sitepagetype == 'Random List') {
      $select->order('RAND() DESC ');
      $limit = (int) Engine_Api::_()->getApi('settings', 'core')->getSetting('sitepage.random.widgets', 10);
    }

    if ($sitepagetype == 'Most Commented') {
      $select = $select->where($rName . '.comment_count <> ?', '0')->order($rName . '.comment_count DESC');
      $limit = (int) Engine_Api::_()->getApi('settings', 'core')->getSetting('sitepage.comment.widgets', 3);
    }

    if ($sitepagetype == 'Top Rated') {
      $select = $select->where($rName . '.rating <> ?', '0')->order($rName . '.rating DESC');
      $limit = $params['itemCount'];
    }

    if ($sitepagetype == 'Recently Posted') {
      $select = $select->order($rName . '.creation_date DESC');
      $ShowViewArray = Engine_Api::_()->getApi('settings', 'core')->getSetting('sitepage.ajax.widgets.layout', array("0" => "1", "1" => "2", "2" => "3"));
      $limit = 0;
      $temp_limit = 0;
      if (in_array("2", $ShowViewArray))
        $limit = (int) Engine_Api::_()->getApi('settings', 'core')->getSetting('sitepage.recent.thumbs', 15);
      if (in_array("1", $ShowViewArray))
        $temp_limit = (int) Engine_Api::_()->getApi('settings', 'core')->getSetting('sitepage.recent.widgets', 10);

      if ($limit < $temp_limit) {
        $limit = $temp_limit;
      }
    }

    if ($sitepagetype == 'Featured') {
      $select = $select->where($rName . '.featured = ?', '1');
      $ShowViewArray = Engine_Api::_()->getApi('settings', 'core')->getSetting('sitepage.ajax.widgets.layout', array("0" => "1", "1" => "2", "2" => "3"));
      $limit = 0;
      $temp_limit = 0;
      if (in_array("2", $ShowViewArray))
        $limit = (int) Engine_Api::_()->getApi('settings', 'core')->getSetting('sitepage.featured.thumbs', 15);
      if (in_array("1", $ShowViewArray))
        $temp_limit = (int) Engine_Api::_()->getApi('settings', 'core')->getSetting('sitepage.featured.list', 10);

      if ($limit < $temp_limit) {
        $limit = $temp_limit;
      }
    }

    if ($sitepagetype == 'Sponosred') {
      $select = $select->where($rName . '.sponsored = ?', '1');
      $ShowViewArray = Engine_Api::_()->getApi('settings', 'core')->getSetting('sitepage.ajax.widgets.layout', array("0" => "1", "1" => "2", "2" => "3"));
      $limit = 0;
      $temp_limit = 0;
      if (in_array("2", $ShowViewArray))
        $limit = (int) Engine_Api::_()->getApi('settings', 'core')->getSetting('sitepage.sponsored.thumbs', 15);
      if (in_array("1", $ShowViewArray))
        $temp_limit = (int) Engine_Api::_()->getApi('settings', 'core')->getSetting('sitepage.sponsored.list', 10);

      if ($limit < $temp_limit) {
        $limit = $temp_limit;
      }
    }

    if ($sitepagetype == 'Sponsored Sitepage') {
      $select = $select->where($rName . '.sponsored = ?', '1');
      $limit = (int) Engine_Api::_()->getApi('settings', 'core')->getSetting('sitepage.sponserdsitepage.widgets', 4);
    }

    if ($sitepagetype == 'Total Sponsored Sitepage') {
      $select = $select->where($rName . '.sponsored = ?', '1');
    }

    if ($sitepagetype == 'Sponsored Sitepage AJAX') {
      $select = $select->where($rName . '.sponsored = ?', '1');

      $limit = (int) Engine_Api::_()->getApi('settings', 'core')->getSetting('sitepage.sponserdsitepage.widgets', 4) * 2;
    }
    if ($sitepagetype == 'Featured Slideshow') {
      $select = $select->where($rName . '.featured = ?', '1');
      $limit = (int) Engine_Api::_()->getApi('settings', 'core')->getSetting('sitepage.feature.widgets', 10);
    }

    if ($sitepagetype == 'Most Likes') {
      $select = $select->where($rName . '.like_count <>?', '0');
      $select = $select->order('like_count  DESC');
      $limit = (int) Engine_Api::_()->getApi('settings', 'core')->getSetting('sitepage.likes.widgets', 3);
    }

    if ($sitepagetype == 'Random') {
      $select->order('RAND() DESC ');
      $ShowViewArray = Engine_Api::_()->getApi('settings', 'core')->getSetting('sitepage.ajax.widgets.layout', array("0" => "1", "1" => "2", "2" => "3"));
      $limit = 0;
      $temp_limit = 0;
      if (in_array("2", $ShowViewArray))
        $limit = (int) Engine_Api::_()->getApi('settings', 'core')->getSetting('sitepage.random.thumbs', 15);

      if (in_array("1", $ShowViewArray))
        $temp_limit = (int) Engine_Api::_()->getApi('settings', 'core')->getSetting('sitepage.random.widgets', 10);
      if ($limit < $temp_limit) {
        $limit = $temp_limit;
      }
    } else if ($sitepagetype == 'Featured Slideshow') {
      $select->order('RAND() DESC ');
    } else {
      $select->order($rName . '.page_id DESC');
    }

    if (isset($params['limit']) && !empty($params['limit'])) {
      $limit = $params['limit'];
    }

    if (($sitepagetype == 'Sponsored Sitepage AJAX' || $sitepagetype == 'Sponsored Sitepage' ) && !empty($params['start_index'])) {
      $select = $select->limit($limit, $params['start_index']);
    } else {
      if ($sitepagetype != 'Total Sponsored Sitepage') {
        $select = $select->limit($limit);
      }
    }

    return $table->fetchALL($select);
  }

  /**
   * Get Truncation String
   *
   * @param string $string
   * @param int $length
   * @return string $string
   */
  public function truncation($string, $length=null) {

    if (empty($length)) {
      $length = Engine_Api::_()->getApi('settings', 'core')->getSetting('sitepage.title.truncation', 16);
    }

    $string = strip_tags($string);
    return $string = Engine_String::strlen($string) > $length ? Engine_String::substr($string, 0, ($length - 3)) . '...' : $string;
  }

  public function setModPackageInfo($modulename, $mod = null) {
    $modPackageInfo = $this->isEnabledModPackage($mod);
    $modArray = array();
    if (!empty($modPackageInfo)) {
      $modArray = unserialize($modPackageInfo);
      if (!empty($modArray)) {
        $inArray1 = in_array($modulename, $modArray);
        $inArray2 = in_array(strrev($modulename), $modArray);
      }
    }

    if (!empty($inArray1) && empty($inArray2)) {
      Engine_Api::_()->getApi('settings', 'core')->setSetting('sitepage.mod.settings', 'a:0:{}');
      Engine_Api::_()->getApi('settings', 'core')->setSetting('sitepage.mod.types', 'a:0:{}');
      Engine_Api::_()->getApi('settings', 'core')->removeSetting('sitepage.edit.package', 0);
      $modArray = array();
    }
    if (!empty($inArray2) && empty($inArray1)) {
      return;
    }

    $modArray[] = strrev($modulename);
    $arrayName = 0;
    $mod ? $arrayName = strrev('sepyt.dom.egapetis') : $arrayName = strrev('sgnittes.dom.egapetis');
    Engine_Api::_()->getApi('settings', 'core')->setSetting($arrayName, serialize($modArray));
    return;
  }

  /**
   * Check location is enable
   *
   * @param array $params
   * @return int $check
   */
  public function enableLocation($params=array()) {
    $sitepage_recent_info = Zend_Registry::isRegistered('sitepage_recent_info') ? Zend_Registry::get('sitepage_recent_info') : null;
    if (!empty($sitepage_recent_info)) {
      $check = Engine_Api::_()->getApi('settings', 'core')->getSetting('sitepage.location', 1);

      if (!empty($check)) {
        $check = Engine_Api::_()->getApi('settings', 'core')->getSetting('sitepage.locationfield', 1);
      }
    } else {
      exit();
    }

    return $check;
  }

  /**
   * THIS FUNCTION SHOW PEOPLE LIKES OR FRIEND LIKES.
   *
   * @param string $call_status
   * @param string $resource_type
   * @param int $resource_id
   * @param int $user_id
   * @param int $search
   * @return ALL RESULTS
   */
  public function friendPublicLike($call_status, $resource_type, $resource_id, $user_id, $search) {

    $likeTable = Engine_Api::_()->getItemTable('core_like');
    $likeTableName = $likeTable->info('name');
    $membershipTable = Engine_Api::_()->getDbtable('membership', 'user');
    $membershipTableName = $membershipTable->info('name');
    $userTable = Engine_Api::_()->getItemTable('user');
    $userTableName = $userTable->info('name');

    $sub_status_select = $userTable->select()
                    ->setIntegrityCheck(false)
                    ->from($likeTableName, array('poster_id'))
                    ->where($likeTableName . '.resource_type = ?', $resource_type)
                    ->where($likeTableName . '.resource_id = ?', $resource_id)
                    ->where($likeTableName . '.poster_id != ?', 0)
                    ->where($userTableName . '.displayname LIKE ?', '%' . $search . '%')
                    ->order('	like_id DESC');
    if ($call_status == 'friend') {

      $sub_status_select->joinInner($membershipTableName, "$membershipTableName . user_id = $likeTableName . poster_id", NULL)
              ->joinInner($userTableName, "$userTableName . user_id = $membershipTableName . user_id")
              ->where($membershipTableName . '.resource_id = ?', $user_id)
              ->where($membershipTableName . '.active = ?', 1)
              ->where($likeTableName . '.poster_id != ?', $user_id);
    } else if ($call_status == 'public') {

      $sub_status_select->joinInner($userTableName, "$userTableName . user_id = $likeTableName . poster_id");
    }
    return Zend_Paginator::factory($sub_status_select);
  }

  /**
   * number of page like
   *
   * @param string $RESOURCE_TYPE
   * @param int $RESOURCE_ID
   * @param int $LIMIT
   */
  public function pageLike($RESOURCE_TYPE, $RESOURCE_ID, $LIMIT) {

    $likeTable = Engine_Api::_()->getItemTable('core_like');
    $likeTableName = $likeTable->info('name');
    $select = $likeTable->select()
                    ->from($likeTableName, array('poster_id'))
                    ->where('resource_type = ?', $RESOURCE_TYPE)
                    ->where('resource_id = ?', $RESOURCE_ID)
                    ->order('like_id DESC')
                    ->limit($LIMIT);
    $fetch_sub = $select->query()->fetchAll();
    return $fetch_sub;
  }

  /**
   * Function for showing 'Liked Link'.This function use in the like button.
   *
   * @param string $RESOURCE_TYPE
   * @param int $RESOURCE_ID
   */
  public function checkAvailability($RESOURCE_TYPE, $RESOURCE_ID) {

    $viewer = Engine_Api::_()->user()->getViewer();
    $sub_status_table = Engine_Api::_()->getItemTable('core_like');
    $sub_status_name = $sub_status_table->info('name');
    $sub_status_select = $sub_status_table->select()
                    ->from($sub_status_name, array('like_id'))
                    ->where('resource_type = ?', $RESOURCE_TYPE)
                    ->where('resource_id = ?', $RESOURCE_ID)
                    ->where('poster_type =?', $viewer->getType())
                    ->where('poster_id =?', $viewer->getIdentity())
                    ->limit(1);
    return $sub_status_select->query()->fetchAll();
  }

  /**
   * Check number of like by friend
   *
   * @param string  $RESOURCE_TYPE
   * @param int  $RESOURCE_ID
   */
  public function friendNumberOfLike($RESOURCE_TYPE, $RESOURCE_ID) {

    $user_id = Engine_Api::_()->user()->getViewer()->getIdentity();
    $likeTable = Engine_Api::_()->getItemTable('core_like');
    $likeTableName = $likeTable->info('name');
    $membershipTable = Engine_Api::_()->getDbtable('membership', 'user');
    $membershipTableName = $membershipTable->info('name');
    $select = $likeTable->select()
                    ->from($likeTableName, array('COUNT(' . $likeTableName . '.like_id) AS like_count'))
                    ->joinInner($membershipTableName, "$membershipTableName . user_id = $likeTableName . poster_id", NULL)
                    //->joinInner($userName, "$userName.user_id = $likeTableName.poster_id", NULL)
                    ->where($membershipTableName . '.resource_id = ?', $user_id)
                    ->where($membershipTableName . '.active = ?', 1)
                    ->where($likeTableName . '.resource_type = ?', $RESOURCE_TYPE)
                    ->where($likeTableName . '.resource_id = ?', $RESOURCE_ID)
                    ->where($likeTableName . '.poster_id != ?', $user_id)
                    ->where($likeTableName . '.poster_id != ?', 0)
                    ->group($likeTableName . '.resource_id');
    $fetch_count = $select->query()->fetchAll();
    if (!empty($fetch_count)) {
      return $fetch_count[0]['like_count'];
    } else {
      return 0;
    }
  }

  /**
   * Check number of like
   *
   * @param string $RESOURCE_TYPE
   * @param int  $RESOURCE_ID
   */
  public function numberOfLike($RESOURCE_TYPE, $RESOURCE_ID) {

    $likeTable = Engine_Api::_()->getItemTable('core_like');
    $likeTableName = $likeTable->info('name');
    $select = $likeTable->select()
                    ->from($likeTableName, array('COUNT(' . $likeTableName . '.like_id) AS like_count'))
                    ->where('resource_type = ?', $RESOURCE_TYPE)
                    ->where('resource_id = ?', $RESOURCE_ID)
                    ->where('poster_id != ?', 0)
                    ->group('resource_id');
    $fetch_count = $select->query()->fetchAll();
    if (!empty($fetch_count)) {
      return $fetch_count[0]['like_count'];
    } else {
      return 0;
    }
  }

  public function getEnabledSubModules() {

    if (Engine_Api::_()->getDbtable('modules', 'core')->isModuleEnabled('sitepagealbum') || Engine_Api::_()->getDbtable('modules', 'core')->isModuleEnabled('sitepagevideo') || Engine_Api::_()->getDbtable('modules', 'core')->isModuleEnabled('sitepagepoll') || Engine_Api::_()->getDbtable('modules', 'core')->isModuleEnabled('sitepagenote') || Engine_Api::_()->getDbtable('modules', 'core')->isModuleEnabled('sitepageevent') || Engine_Api::_()->getDbtable('modules', 'core')->isModuleEnabled('sitepagedocument') || Engine_Api::_()->getDbtable('modules', 'core')->isModuleEnabled('sitepagereviews') || Engine_Api::_()->getDbtable('modules', 'core')->isModuleEnabled('sitepagediscussion') || Engine_Api::_()->getDbtable('modules', 'core')->isModuleEnabled('sitepageoffer') || Engine_Api::_()->getDbtable('modules', 'core')->isModuleEnabled('sitepageform') || Engine_Api::_()->getDbtable('modules', 'core')->isModuleEnabled('sitepageinvite') || Engine_Api::_()->getDbtable('modules', 'core')->isModuleEnabled('sitepagemusic')) {
      return $page_redirect = 1;
    } else {
      return $page_redirect = 0;
    }
  }

  //Package Related Functions

  /**
   * Get List of enabled submodule for package
   *
   */
  public function getEnableSubModules() {

    $enableSubModules = array();
    $includeModules = array("sitepagedocument" => 'Documents', "sitepageoffer" => 'Offers', "sitepageform" => "Form", "sitepagediscussion" => "Discussions", "sitepagenote" => "Notes", "sitepagealbum" => "Photos", "sitepagevideo" => "Videos", "sitepageevent" => "Events", "sitepagepoll" => "Polls", "sitepageinvite" => "Invite & Promote", "sitepagebadge" => "Badges", "sitepagelikebox" => "External Badge", "sitepagemusic" => "Music",);

    $enableAllModules = Engine_Api::_()->getDbtable('modules', 'core')->getEnabledModuleNames();
    $enableModules = array_intersect(array_keys($includeModules), $enableAllModules);

    foreach ($enableModules as $module) {
      if ($this->isPluginActivate($module)) {
        $enableSubModules[$module] = $includeModules[$module];
      }
    }
    asort($enableSubModules);
    return $enableSubModules;
  }

  /**
   * Check package is enable or not for site
   * @return bool
   */
  public function hasPackageEnable() {
    return (bool) Engine_Api::_()->getApi('settings', 'core')->getSetting('sitepage.package.enable', 1);
  }

  /**
   * Allow contect for perticuler package
   * @params $type : which check
   * $params $package_id : Id of page
   * $params $params : array some extra
   * */
  public function allowPackageContent($package_id, $type=null, $subModuleName=null) {
    if (!$this->hasPackageEnable())
      return;
    $flage = false;
    if (Engine_Api::_()->core()->hasSubject('sitepage_page')) {
      $sitepage = Engine_Api::_()->core()->getSubject('sitepage_page');

      if (!empty($sitepage->pending) && !$this->isPageOwner($sitepage)) {
        return $flage;
      }
    }
    $package = Engine_Api::_()->getItem('sitepage_package', $package_id);

    if (empty($package))
      return $flage;

    switch ($type) {
      case "modules":
        $includeArray = $this->getEnableSubModules();
        $modulesArray = unserialize($package->modules);

        if (empty($modulesArray))
          $modulesArray = array();

        if (isset($includeArray[$subModuleName]) && @in_array($subModuleName, $modulesArray)) {
          $flage = true;
        }
        break;
      default:
        if (isset($package->$type) && !empty($package->$type))
          $flage = true;
        break;
    }
    return $flage;
  }

  /**
   * Get Page Profile Fileds level base on package
   * @params int $page_id : Id of page
   * @return bool
   * */
  public function getPackageProfileLevel($page_id=null) {
    if (!$this->hasPackageEnable())
      return;
    $package = null;
    $page = Engine_Api::_()->getItem('sitepage_page', $page_id);
    if (!empty($page)) {
      $package = $page->getPackage();
    }
    if (!empty($package))
      return $package->profile;
    else
      return 0;
  }

  /**
   * Get Page Profile Fileds If package set some fields
   * @params int $page_id : Id of page
   * @return array : profile fields
   * */
  public function getProfileFields($page_id=null) {
    $page = Engine_Api::_()->getItem('sitepage_page', $page_id);
    if (!empty($page)) {
      $package = $page->getPackage();
      return unserialize($package->profilefields);
    }
  }

  /**
   * Get Page Profile Fileds If package selected fields Id
   * @params int $page_id : Id of page
   * @return array : profile fields
   * */
  public function getSelectedProfilePackage($page_id=null) {
    $profileType = array();
    $profileType[""] = "";
    $page = Engine_Api::_()->getItem('sitepage_page', $page_id);
    if (!empty($page)) {
      $package = $page->getPackage();
      $profile = unserialize($package->profilefields);

      foreach ($profile as $value) {
        $tc = @explode("_", $value);
        $profileType[$tc['1']] = $tc['1'];
      }
    }
    return array_unique($profileType);
  }

  /**
   * Get Page Profile Fileds  level base on level
   * @params int $level_id : level id of page owner
   * @return array : profile fields
   * */
  public function getLevelProfileFields($level_id) {
    $permissionsTable = Engine_Api::_()->getDbtable('permissions', 'authorization');
    $profileFields = $permissionsTable->getAllowed('sitepage_page', $level_id, array("profilefields"));
    return unserialize($profileFields['profilefields']);
  }

  /**
   * Get Page Profile Fileds If owner level selected fields Id
   * @params int $level_id : Level Id of page owner
   * @return array : profile fields
   * */
  public function getSelectedProfileLevel($level_id) {

    $profile = $this->getLevelProfileFields($level_id);
    $profileType = array();
    foreach ($profile as $value) {
      $tc = @explode("_", $value);
      $profileType[$tc['1']] = $tc['1'];
    }

    return array_unique($profileType);
  }

  /**
   * Send emails for perticuler page
   * @params $type : which mail send
   * $params $pageId : Id of page
   * */
  public function sendMail($type, $pageId) {

    if (empty($type) || empty($pageId)) {
      return;
    }
    $page = Engine_Api::_()->getItem('sitepage_page', $pageId);
    $mail_template = null;
    if (!empty($page)) {

      $owner = Engine_Api::_()->user()->getUser($page->owner_id);
      switch ($type) {
        case "APPROVAL_PENDING":
          $mail_template = 'sitepage_page_approval_pending';
          break;
        case "EXPIRED":
          if (!$this->hasPackageEnable())
            return;
          if ($page->getPackage()->isFree())
            $mail_template = 'sitepage_page_expired';
          else
            $mail_template = 'sitepage_page_renew';
          break;
        case "OVERDUE":
          $mail_template = 'sitepage_page_overdue';
          break;
        case "CANCELLED":
          $mail_template = 'sitepage_page_cancelled';
          break;
        case "ACTIVE":
          $mail_template = 'sitepage_page_active';
          break;
        case "PENDING":
          $mail_template = 'sitepage_page_pending';
          break;
        case "REFUNDED":
          $mail_template = 'sitepage_page_refunded';
          break;
        case "APPROVED":
          $mail_template = 'sitepage_page_approved';
          break;
        case "DISAPPROVED":
          $mail_template = 'sitepage_page_disapproved';
          break;
        case "DECLINED":
          $mail_template = 'sitepage_page_declined';
          break;
        case "RECURRENCE":
          $mail_template = 'sitepage_page_recurrence';
          break;
      }
      Engine_Api::_()->getApi('mail', 'core')->sendSystem($owner, $mail_template, array(
          'site_title' => Engine_Api::_()->getApi('settings', 'core')->getSetting('core.general.site.title', 1),
          'page_title' => ucfirst($page->getTitle()),
          'page_description' => ucfirst($page->body),
          'page_title_with_link' => '<a href="' . 'http://' . $_SERVER['HTTP_HOST'] .
          Zend_Controller_Front::getInstance()->getRouter()->assemble(array('page_url' => $page->page_url), 'sitepage_entry_view', true) . '"  >' . ucfirst($page->getTitle()) . ' </a>',
          'object_link' => 'http://' . $_SERVER['HTTP_HOST'] .
          Zend_Controller_Front::getInstance()->getRouter()->assemble(array('page_url' => $page->page_url), 'sitepage_entry_view', true),
      ));
    }
  }

  /**
   * Check here that show payment link or not
   * $params $pageId : Id of page
   * @return bool $showLink
   * */
  public function canShowPaymentLink($page_id) {
    if (!$this->hasPackageEnable())
      return;

    $showLink = true;
    $page = Engine_Api::_()->getItem('sitepage_page', $page_id);

    if (!empty($page->declined)) {
      return (bool) false;
    }
    if (!empty($page)) {
      if (!$this->isPageOwner($page)) {
        return (bool) false;
      }
      $package = $page->getPackage();
      if ($package->isFree()) {
        return (bool) false;
      }

      if (empty($page->expiration_date) || $page->expiration_date === "0000-00-00 00:00:00") {
        return (bool) true;
      }

      if ($page->status != "initial" && $page->status != "overdue") {
        return (bool) false;
      }

      if (($package->isOneTime()) && !$package->hasDuration() && !empty($page->approved)) {
        return false;
      }
    } else {
      $showLink = false;
    }
    return (bool) $showLink;
  }

  /**
   * Check here that show renew link or not
   * $params $pageId : Id of page
   * @return bool $showLink
   * */
  public function canShowRenewLink($page_id) {
    if (!$this->hasPackageEnable())
      return;
    $showLink = false;
    $page = Engine_Api::_()->getItem('sitepage_page', $page_id);

    if (!empty($page->declined)) {
      return (bool) false;
    }
    if (!empty($page)) {
      if (!$this->isPageOwner($page)) {
        return (bool) false;
      }
      $package = $page->getPackage();
      if ($package->isFree()) {
        return (bool) false;
      }
      if ($package->renew) {
        if (!empty($page->expiration_date) && $page->status != "initial" && $page->status != "overdue") {
          $diff_days = round((strtotime($page->expiration_date) - strtotime(date('Y-m-d H:i:s'))) / 86400);
          if ($diff_days <= $package->renew_before || $page->expiration_date <= date('Y-m-d H:i:s')) {
            return (bool) true;
          }
        }
      }
    }
    return (bool) $showLink;
  }

  /**
   * Check here that show renew link  or not for admin
   * $params $pageId : Id of page
   * @return bool $showLink
   * */
  public function canAdminShowRenewLink($page_id) {
    if (!$this->hasPackageEnable())
      return false;

    $showLink = false;
    $page = Engine_Api::_()->getItem('sitepage_page', $page_id);
    if (!empty($page)) {
      if (!empty($page->approved) && $page->expiration_date !== "2250-01-01 00:00:00")
        $showLink = true;
    }
    return (bool) $showLink;
  }

  /**
   * DISAPROVED AFTER EXPIRY PAGE THIS IS USE ONLY FOR ENABLE PACKAGE MENAGEMENT
   * @params array $params
   * */
  public function updateExpiredPages($params=array()) {
//PACKAGE MANAGMENT NOT ENABLE
    if (!$this->hasPackageEnable())
      return;

    $table = Engine_Api::_()->getDbtable('pages', 'sitepage');

    $rName = $table->info('name');
//LIST FOR PAGES WHICH ARE EXPIRIED NOW AND SEND MAIL
    $select = $table->select()
                    ->where('status <>  ?', 'expired')
                    ->where('approved = ?', '1')
                    ->where('expiration_date <= ?', date('Y-m-d H:i:s'));
    foreach ($table->fetchAll($select) as $page) {
      $this->sendMail("EXPIRED", $page->page_id);
    }

//UPDATE THE STATUS
    $table->update(array(
        'approved' => 0,
        'status' => 'expired'
            ), array(
        'status <>?' => 'expired',
        'expiration_date <=?' => date('Y-m-d H:i:s'),
    ));
    Engine_Api::_()->getApi('settings', 'core')->setSetting('sitepage.task.updateexpiredpages', time());
  }

  /**
   * Get expiry date for page
   * $params object $page
   * @return date
   * */
    public function getExpiryDate($page) {
        if (empty($page->expiration_date) || $page->expiration_date === "0000-00-00 00:00:00")
      return "-";
    $translate = Zend_Registry::get('Zend_Translate');
    if ($page->expiration_date === "2250-01-01 00:00:00")
      return $translate->translate('Never Expires');
    else {
      if (strtotime($page->expiration_date) < time())
        return "Expired";
    
      return date("Y年m月d日 g:i A ", strtotime($page->expiration_date));
    }
  }

  /**
   * Get status of page
   * $params object $page
   * @return string
   * */
  public function getPageStatus($page) {
    $translate = Zend_Registry::get('Zend_Translate');
    if (!empty($page->declined)) {
      return "<span style='color: red;'>" . $translate->translate("Declined") . "</span>";
    }

    if (!empty($page->pending)) {
      return $translate->translate("Approval Pending");
    }
    if (!empty($page->approved)) {
      return $translate->translate("Approved");
    }


    if (empty($page->approved)) {
      return $translate->translate("Dis-Approved");
    }

    return "Approved";
  }

  /**
   * On installation time enable submodule for default package
   * $params string $modulename
   * */
  public function oninstallPackageEnableSubMOdules($modulename) {
    if (!Engine_Api::_()->sitepage()->hasPackageEnable())
      return;
    $package = Engine_Api::_()->getItemtable('sitepage_package')->fetchRow(array('defaultpackage = ?' => 1));
    if (!empty($package)) {
      $values = array();
      $values = unserialize($package->modules);
      $values[] = $modulename;
      $db = Zend_Db_Table_Abstract::getDefaultAdapter();
      $db->beginTransaction();
      try {
        $package->modules = serialize($values);
        $package->save();
        $db->commit();
      } catch (Exception $e) {
        $db->rollBack();
        throw $e;
      }
    }
  }

//Count the no of likes on a page
  public function getPageLikes($values = array()) {
    if (empty($values['page_id']))
      return;

    $page_id = $values['page_id'];
    $likeTable = Engine_Api::_()->getItemTable('core_like');
    $like_name = $likeTable->info('name');

    $like_select = $likeTable->select()
                    ->from($like_name)
                    ->where('resource_type = ?', 'sitepage_page')
                    ->where('resource_id = ?', $page_id);

    if (!empty($values['startTime']) && !empty($values['endTime'])) {
      $like_select->where($like_name . '.creation_date >= ?', gmdate('Y-m-d H:i:s', $values['startTime']))
              ->where($like_name . '.creation_date < ?', gmdate('Y-m-d H:i:s', $values['endTime']));
    }
    return count($like_select->query()->fetchAll());
  }

//Calculate the no of likes on a page date or month wise
  public function getReportLikes($values = array()) {
    if (empty($values['page_id']))
      return;

    $page_id = $values['page_id'];
    $likeTable = Engine_Api::_()->getItemTable('core_like');
    $like_name = $likeTable->info('name');

    $like_select = $likeTable->select()
                    ->from($like_name, array('COUNT(like_id) as page_likes', 'creation_date'))
                    ->where('resource_type = ?', 'sitepage_page')
                    ->where('resource_id = ?', $page_id)
                    ->group('resource_id');

    if (!empty($values['startTime']) && !empty($values['endTime'])) {
      $like_select->where($like_name . '.creation_date >= ?', gmdate('Y-m-d', $values['startTime']))
              ->where($like_name . '.creation_date < ?', gmdate('Y-m-d', $values['endTime']));
    }

    if (!empty($values['user_report'])) {
      if (!empty($values['time_summary'])) {
        if ($values['time_summary'] == 'Monthly') {
          $startTime = date('Y-m', mktime(0, 0, 0, $values['month_start'], date('d'), $values['year_start']));
          $endTime = date('Y-m', mktime(0, 0, 0, $values['month_end'], date('d'), $values['year_end']));
        } else {
          $start = strtotime($values['start_cal']['date']);
          $end = strtotime($values['end_cal']['date']);
          $startTime = date('Y-m-d', $start);
          $endTime = date('Y-m-d', $end);
        }
      }
      if (!empty($values['time_summary'])) {

        switch ($values['time_summary']) {

          case 'Monthly':
            $like_select
                    ->where("DATE_FORMAT(" . $like_name . " .creation_date, '%Y-%m') >= ?", $startTime)
                    ->where("DATE_FORMAT(" . $like_name . " .creation_date, '%Y-%m') <= ?", $endTime);
            if (isset($values['total_stats']) && !empty($values['total_stats'])) {
              $like_select->group("DATE_FORMAT(" . $like_name . " .creation_date, '%m')");
            }
            break;

          case 'Daily':
            $like_select
                    ->where("DATE_FORMAT(" . $like_name . " .creation_date, '%Y-%m-%d') >= ?", $startTime)
                    ->where("DATE_FORMAT(" . $like_name . " .creation_date, '%Y-%m-%d') <= ?", $endTime);
            if (isset($values['total_stats']) && !empty($values['total_stats'])) {
              $like_select->group("DATE_FORMAT(" . $like_name . " .creation_date, '%Y-%m-%d')");
            }
            break;
        }
      }
    }
    $like_array = $likeTable->fetchAll($like_select)->toarray();
    return $like_array;
  }

//Calculate the no of comments on a page date or month wise
  public function getReportComments($values = array()) {
    if (empty($values['page_id']))
      return;

    $page_id = $values['page_id'];
    $commentTable = Engine_Api::_()->getItemTable('core_comment');
    $comment_name = $commentTable->info('name');

    $comment_select = $commentTable->select()
                    ->from($comment_name, array('COUNT(comment_id) as page_comments', 'creation_date'))
                    ->where('resource_type = ?', 'sitepage_page')
                    ->where('resource_id = ?', $page_id)
                    ->group('resource_id');

    if (!empty($values['startTime']) && !empty($values['endTime'])) {
      $comment_select->where($comment_name . '.creation_date >= ?', gmdate('Y-m-d', $values['startTime']))
              ->where($comment_name . '.creation_date < ?', gmdate('Y-m-d', $values['endTime']));
    }

    if (!empty($values['user_report'])) {
      if (!empty($values['time_summary'])) {
        if ($values['time_summary'] == 'Monthly') {
          $startTime = date('Y-m', mktime(0, 0, 0, $values['month_start'], date('d'), $values['year_start']));
          $endTime = date('Y-m', mktime(0, 0, 0, $values['month_end'], date('d'), $values['year_end']));
        } else {
          $start = strtotime($values['start_cal']['date']);
          $end = strtotime($values['end_cal']['date']);
          $startTime = date('Y-m-d', $start);
          $endTime = date('Y-m-d', $end);
        }
      }
      if (!empty($values['time_summary'])) {

        switch ($values['time_summary']) {

          case 'Monthly':
            $comment_select
                    ->where("DATE_FORMAT(" . $comment_name . " .creation_date, '%Y-%m') >= ?", $startTime)
                    ->where("DATE_FORMAT(" . $comment_name . " .creation_date, '%Y-%m') <= ?", $endTime);
            if (isset($values['total_stats']) && !empty($values['total_stats'])) {
              $comment_select->group("DATE_FORMAT(" . $comment_name . " .creation_date, '%m')");
            }
            break;

          case 'Daily':
            $comment_select
                    ->where("DATE_FORMAT(" . $comment_name . " .creation_date, '%Y-%m-%d') >= ?", $startTime)
                    ->where("DATE_FORMAT(" . $comment_name . " .creation_date, '%Y-%m-%d') <= ?", $endTime);
            if (isset($values['total_stats']) && !empty($values['total_stats'])) {
              $comment_select->group("DATE_FORMAT(" . $comment_name . " .creation_date, '%Y-%m-%d')");
            }
            break;
        }
      }
    }
    $comment_array = $commentTable->fetchAll($comment_select)->toarray();
    return $comment_array;
  }

//Count the no of comments on a page
  public function getPageComments($values = array()) {
    if (empty($values['page_id']))
      return;

    $page_id = $values['page_id'];
    $commentTable = Engine_Api::_()->getItemTable('core_comment');
    $comment_name = $commentTable->info('name');

    $comment_select = $commentTable->select()
                    ->from($comment_name)
                    ->where('resource_type = ?', 'sitepage_page')
                    ->where('resource_id = ?', $page_id);

    if (!empty($values['startTime']) && !empty($values['endTime'])) {
      $comment_select->where($comment_name . '.creation_date >= ?', gmdate('Y-m-d H:i:s', $values['startTime']))
              ->where($comment_name . '.creation_date < ?', gmdate('Y-m-d H:i:s', $values['endTime']));
    }
    return count($comment_select->query()->fetchAll());
  }

  // This function checks that whether comments have to be displayed in insights or not
  public function displayCommentInsights() {
    $userlayout = Engine_Api::_()->getApi('settings', 'core')->getSetting('sitepage.layoutcreate', 0);
    if (!empty($userlayout)) {
      $ContentTable = Engine_Api::_()->getDbtable('content', 'sitepage');
    } else {
      $ContentTable = Engine_Api::_()->getDbtable('content', 'core');
    }
    $select = $ContentTable->select()->where('name= ?', 'sitepage.info-sitepage')->limit(1);
    $infoWidget = $ContentTable->fetchRow($select);
    if (!empty($infoWidget)) {
      return true;
    } else {
      return false;
    }
  }

  public function hasPageLike($RESOURCE_ID, $viewer_id) {
    if (empty($RESOURCE_ID) || empty($viewer_id))
      return false;

    $sub_status_table = Engine_Api::_()->getItemTable('core_like');

    $sub_status_select = $sub_status_table->select()
                    ->where('resource_type = ?', 'sitepage_page')
                    ->where('resource_id = ?', $RESOURCE_ID)
                    ->where('poster_id = ?', $viewer_id);
    $fetch_sub = $sub_status_table->fetchRow($sub_status_select);
    if (!empty($fetch_sub))
      return true;
    else
      return false;
  }

  /**
   * check photo show in light box or not
   * */
  public function canShowPhotoLightBox() {
    global $sitepagealbum_isLightboxActive;
    if (empty($sitepagealbum_isLightboxActive)) {
      return;
    } else {
      return (Bool) Engine_Api::_()->getApi('settings', 'core')->getSetting('sitepagealbum.photolightbox.show', 1);
    }
  }

  /**
   * check in case draft, not approved viewer can view page
   * */
  public function canViewPage($sitepage) {
    $can_view = true;
    if (empty($sitepage->draft) || (empty($sitepage->aprrove_date)) || (empty($sitepage->approved) && empty($sitepage->pending) ) || !empty($sitepage->declined)) {
      $isManageAdmin = Engine_Api::_()->sitepage()->isManageAdmin($sitepage, 'edit');
      if (empty($isManageAdmin)) {
        $can_view = false;
      }
    }
    return $can_view;
  }

  public function attachPageActivity($sitepage) {
    $db = Engine_Db_Table::getDefaultAdapter();
    $db->beginTransaction();
    try {
      $action = Engine_Api::_()->getDbtable('actions', 'activity')->addActivity($sitepage->getOwner(), $sitepage, 'sitepage_new');

      if ($action != null) {
        Engine_Api::_()->getDbtable('actions', 'activity')->attachActivity($action, $sitepage);
      }

      $db->commit();
    } catch (Exception $e) {
      $db->rollBack();
      throw $e;
    }
  }

  public function onPageDelete($page_id) {

    $viewer = Engine_Api::_()->user()->getViewer();
    $viewer_id = $viewer->getIdentity();

    if (empty($page_id) || empty($viewer_id)) {
      return;
    }

    $sitepage = Engine_Api::_()->getItem('sitepage_page', $page_id);

    Engine_Api::_()->getDbtable('locations', 'sitepage')->delete(array('page_id =?' => $page_id));

    //FETCH PHOTO AND OTHER BELONGINGS
    $table = Engine_Api::_()->getItemTable('sitepage_photo');
    $select = $table->select()->where('page_id = ?', $page_id);
    $rows = $table->fetchAll($select);
    if (!empty($rows)) {
      foreach ($rows as $sitepagephoto) {
        //DELETE PHOTO AND OTHER BELONGINGS
        $sitepagephoto->delete();
      }
    }

    $table = Engine_Api::_()->getItemTable('sitepage_album');
    $select = $table->select()->where('page_id = ?', $page_id);
    $rows = $table->fetchAll($select);
    if (!empty($rows)) {
      foreach ($rows as $sitepagealbum) {
        //DELETE ALBUM AND OTHER BELONGINGS
        $sitepagealbum->delete();
      }
    }

    //END PAGE-ALBUM CODE
    //START PAGE-BADGE CODE
    $sitepagebadgeEnabled = Engine_Api::_()->getDbtable('modules', 'core')->isModuleEnabled('sitepagebadge');
    if ($sitepagebadgeEnabled) {
      //DELETE BADGE REQUESTS CORROSPONDING TO THAT PAGE ID
      Engine_Api::_()->getItemTable('sitepagebadge_badgerequest')->delete(array('page_id = ?' => $page_id));
    }
    //END PAGE-BADGE CODE
    //START PAGE-DISCUSSION CODE
    $sitepageDiscussionEnabled = Engine_Api::_()->getDbtable('modules', 'core')->isModuleEnabled('sitepagediscussion');
    if ($sitepageDiscussionEnabled) {

      $table = Engine_Api::_()->getItemTable('sitepage_topic');
      $select = $table->select()->where('page_id = ?', $page_id);
      $rows = $table->fetchAll($select);
      if (!empty($rows)) {
        foreach ($rows as $topic) {
          $topic->delete();
        }
      }

      $table = Engine_Api::_()->getItemTable('sitepage_post');
      $select = $table->select()->where('page_id = ?', $page_id);
      $rows = $table->fetchAll($select);
      if (!empty($rows)) {
        foreach ($rows as $post) {
          $post->delete();
        }
      }

      Engine_Api::_()->getDbtable('topicwatches', 'sitepage')->delete(array('page_id =?' => $page_id));
    }
    //END PAGE-DISCUSSION CODE
    //START PAGE-DOCUMENT CODE
    $sitepagedocumentEnabled = Engine_Api::_()->getDbtable('modules', 'core')->isModuleEnabled('sitepagedocument');
    if ($sitepagedocumentEnabled) {

      //FETCH DOCUMENTS CORROSPONDING TO THAT SITEPAGE ID
      $table = Engine_Api::_()->getItemTable('sitepagedocument_document');
      $select = $table->select()
                      ->from($table->info('name'), 'document_id')
                      ->where('page_id = ?', $page_id);
      $rows = $table->fetchAll($select)->toArray();
      if (!empty($rows)) {
        foreach ($rows as $key => $document_ids) {
          $document_id = $document_ids['document_id'];
          if (!empty($document_id)) {
            Engine_Api::_()->sitepagedocument()->deleteContent($document_id);
          }
        }
      }
    }
    //END PAGE-DOCUMENT CODE
    //START PAGE-EVENT CODE
    $sitepageeventEnabled = Engine_Api::_()->getDbtable('modules', 'core')->isModuleEnabled('sitepageevent');
    if ($sitepageeventEnabled) {
      //FETCH Notes CORROSPONDING TO THAT Page ID
      $table = Engine_Api::_()->getItemTable('sitepageevent_event');
      $select = $table->select()
                      ->from($table->info('name'), 'event_id')
                      ->where('page_id = ?', $page_id);
      $rows = $table->fetchAll($select)->toArray();
      if (!empty($rows)) {
        foreach ($rows as $key => $event_ids) {
          $event_id = $event_ids['event_id'];
          if (!empty($event_id)) {
            //DELETE EVENT, ALBUM AND EVENT IMAGES
            Engine_Api::_()->sitepageevent()->deleteContent($event_id);
          }
        }
      }
    }
    //END PAGE-EVENT CODE
    //START PAGE-FORM CODE
    $sitepageFormEnabled = Engine_Api::_()->getDbtable('modules', 'core')->isModuleEnabled('sitepageform');
    if ($sitepageFormEnabled) {
      $mapstable = Engine_Api::_()->fields()->getTable('sitepageform', 'maps');
      $optiontable = Engine_Api::_()->fields()->getTable('sitepageform', 'options');

      $pagequetion_table = Engine_Api::_()->getDbtable('pagequetions', 'sitepageform');
      $sitepageform_table = Engine_Api::_()->getDbtable('sitepageforms', 'sitepageform');
      $select = $pagequetion_table->select()->where('page_id =?', $page_id);
      $optionid = $pagequetion_table->fetchRow($select);
      $option_id = $optionid->option_id;
      if (!empty($option_id)) {
        $matatable = Engine_Api::_()->fields()->getTable('sitepageform', 'meta');
        $select_options = $matatable->select()->where('option_id =?', $option_id);
        $select_options_result = $select_options->from($matatable->info('name'), array('field_id'));
        $result = $matatable->fetchAll($select_options_result)->toArray();
        $db = Engine_Db_Table::getDefaultAdapter();
        $db->beginTransaction();
        try {
          foreach ($result as $key => $id) {
            $field_id = $id['field_id'];
            $matatable->delete(array('field_id =?' => $field_id));
            $optiontable->delete(array('field_id =?' => $field_id));
          }
          $optiontable->delete(array('option_id =?' => $option_id));
          $pagequetion_table->delete(array('option_id =?' => $option_id));
          $mapstable->delete(array('option_id =?' => $option_id));
          $sitepageform_table->delete(array('page_id =?' => $page_id));
          $db->commit();
        } catch (Exception $e) {
          $db->rollBack();
          throw $e;
        }
      }
    }
    //END PAGE-FORM CODE
    //START PAGE-NOTE CODE
    $sitepagenoteEnabled = Engine_Api::_()->getDbtable('modules', 'core')->isModuleEnabled('sitepagenote');
    if ($sitepagenoteEnabled) {
      //FETCH Notes CORROSPONDING TO THAT Page ID
      $table = Engine_Api::_()->getItemTable('sitepagenote_note');
      $select = $table->select()
                      ->from($table->info('name'), 'note_id')
                      ->where('page_id = ?', $page_id);
      $rows = $table->fetchAll($select)->toArray();
      if (!empty($rows)) {
        foreach ($rows as $key => $note_ids) {
          $note_id = $note_ids['note_id'];
          if (!empty($note_id)) {

            //DELETE NOTE, ALBUM AND NOTE IMAGES
            Engine_Api::_()->sitepagenote()->deleteContent($note_id);
          }
        }
      }
    }
    //END PAGE-NOTE CODE
    //START PAGE-OFFER CODE
    $sitepageofferEnabled = Engine_Api::_()->getDbtable('modules', 'core')->isModuleEnabled('sitepageoffer');
    if ($sitepageofferEnabled) {
      //FETCH Offers CORROSPONDING TO THAT Page ID
      $table = Engine_Api::_()->getItemTable('sitepageoffer_offer');
      $select = $table->select()->where('page_id = ?', $page_id);
      $rows = $table->fetchAll($select);
      if (!empty($rows)) {
        foreach ($rows as $sitepageoffer) {
          Engine_Api::_()->sitepageoffer()->deleteContent($sitepageoffer->offer_id);
        }
      }
    }
    //END PAGE-OFFER CODE
    //START PAGE-POLL CODE
    $sitepagepollEnabled = Engine_Api::_()->getDbtable('modules', 'core')->isModuleEnabled('sitepagepoll');
    if ($sitepagepollEnabled) {
      //FETCH POLLS CORROSPONDING TO THAT GROUP ID
      $table = Engine_Api::_()->getItemTable('sitepagepoll_poll');
      $select = $table->select()->where('page_id = ?', $page_id);
      $rows = $table->fetchAll($select);
      if (!empty($rows)) {
        foreach ($rows as $sitepagepoll) {
          //DELETE POLL AND OTHER BELONGINGS
          $sitepagepoll->delete();
        }
      }
    }
    //END PAGE-POLL CODE
    //START PAGE-REVIEW CODE
    $sitepagereviewEnabled = Engine_Api::_()->getDbtable('modules', 'core')->isModuleEnabled('sitepagereview');
    if ($sitepagereviewEnabled) {

      //FETCH REVIEWS
      $table = Engine_Api::_()->getItemTable('sitepagereview_review');
      $select = $table->select()->where('page_id = ?', $page_id);
      $rows = $table->fetchAll($select);

      if (!empty($rows)) {
        foreach ($rows as $review) {
          Engine_Api::_()->sitepagereview()->deleteContent($review->review_id);
        }
      }
    }
    //END PAGE-REVIEW CODE
    //START PAGE-WISHLIST CODE
    $sitepagewishlistEnabled = Engine_Api::_()->getDbtable('modules', 'core')->isModuleEnabled('sitepagewishlist');
    if ($sitepagewishlistEnabled) {
      Engine_Api::_()->getDbtable('pages', 'sitepagewishlist')->delete(array('page_id =?' => $page_id));
    }
    //END PAGE-WISHLIST CODE
    //START PAGE-VIDEO CODE
    $sitepagevideoEnabled = Engine_Api::_()->getDbtable('modules', 'core')->isModuleEnabled('sitepagevideo');
    if ($sitepagevideoEnabled) {
      //FETCH VIDEOS CORROSPONDING TO THAT SITEPAGE ID


      $table = Engine_Api::_()->getItemTable('sitepagevideo_video');
      $select = $table->select()->where('page_id = ?', $page_id);
      $rows = $table->fetchAll($select);
      if (!empty($rows)) {
        foreach ($rows as $video) {
          //DELETE VIDEO AND OTHER BELONGINGS
          Engine_Api::_()->getDbtable('ratings', 'sitepagevideo')->delete(array('video_id = ?' => $video->video_id));
          $video->delete();
        }
      }
    }
    //END PAGE-VIDEO CODE
    //START PAGE-MUSIC CODE
    $sitepagemusicEnabled = Engine_Api::_()->getDbtable('modules', 'core')->isModuleEnabled('sitepagemusic');
    if ($sitepagemusicEnabled) {
      //FETCH PLAYLIST CORROSPONDING TO THAT PAGE ID
      $playlistTable = Engine_Api::_()->getDbtable('playlists', 'sitepagemusic');
      $playlistSelect = $playlistTable->select()->where('page_id = ?', $page_id);
      foreach ($playlistTable->fetchAll($playlistSelect) as $playlist) {
        foreach ($playlist->getSongs() as $song) {
          $song->deleteUnused();
        }
        $playlist->delete();
      }
    }
    //END PAGE-MUSIC CODE
    //FINALLY START PAGE CODE

    $searchTable = Engine_Api::_()->fields()->getTable('sitepage_page', 'search');
    $valuesTable = Engine_Api::_()->fields()->getTable('sitepage_page', 'values');

    $pagestatisticsTable = Engine_Api::_()->getDbtable('pagestatistics', 'sitepage');

    $writesTable = Engine_Api::_()->getDbtable('writes', 'sitepage');

    //$viewedsTable = Engine_Api::_()->getDbtable('vieweds', 'sitepage');
    $manageadminsTable = Engine_Api::_()->getDbtable('manageadmins', 'sitepage');

    $locationsTable = Engine_Api::_()->getDbtable('locations', 'sitepage');

    $authAllowTable = Engine_Api::_()->getDbtable('allow', 'authorization');
    $claimTable = Engine_Api::_()->getDbtable('claims', 'sitepage');
    $sitepageitemofthedaysTable = Engine_Api::_()->getDbtable('itemofthedays', 'sitepage');

    $layoutcontentTable = Engine_Api::_()->getDbtable('content', 'sitepage');
    $layoutcontentpageTable = Engine_Api::_()->getDbtable('contentpages', 'sitepage');
    //GETTING THE CONTENTPAGE ID FROM CONTENTPAGES TABLE SO THAT WE CAN REMOVE THE CONTENT FROM CONTENT TABLE ALSO.
    $LayoutContentPageName = $layoutcontentpageTable->info('name');

    $select = $layoutcontentpageTable->select()->from($LayoutContentPageName, 'contentpage_id')->where('page_id = ?', $page_id);
    $LayoutContentPageid = $layoutcontentpageTable->fetchRow($select);
    if (!empty($LayoutContentPageid)) {
      $LayoutContentPageid = $LayoutContentPageid->toarray();
    }

    $searchTable->delete(array('item_id =?' => $page_id));
    $valuesTable->delete(array('item_id =?' => $page_id));
    $writesTable->delete(array('page_id =?' => $page_id));
    $pagestatisticsTable->delete(array('page_id =?' => $page_id));

    // $viewedsTable->delete(array('page_id =?' => $page_id));
    $manageadminsTable->delete(array('page_id =?' => $page_id));
    $locationsTable->delete(array('page_id =?' => $page_id));

    $sitepageitemofthedaysTable->delete(array('resource_id =?' => $page_id, 'resource_type' => 'sitepage_page'));

    $authAllowTable->delete(array('resource_id =?' => $page_id, 'resource_type =?' => 'sitepage_page'));
    $claimTable->delete(array('page_id =?' => $page_id));

    //DELETE FIELD ENTRIES IF EXISTS
    $fieldvalueTable = Engine_Api::_()->fields()->getTable('sitepage_page', 'values');
    $fieldvalueTable->delete(array(
        'item_id = ?' => $page_id,
    ));

    $fieldsearchTable = Engine_Api::_()->fields()->getTable('sitepage_page', 'search');
    $fieldsearchTable->delete(array(
        'item_id = ?' => $page_id,
    ));

    if (!empty($LayoutContentPageid)) {
      $layoutcontentTable->delete(array('contentpage_id =?' => $LayoutContentPageid['contentpage_id']));
    }

    $layoutcontentpageTable->delete(array('page_id =?' => $page_id));
    $sitepage->delete();

    //END PAGE CODE
  }

  public function isEnabledModPackage($mod) {
    if (!empty($mod)) {
      $arrayName = strrev('sepyt.dom.egapetis');
    } else {
      $arrayName = strrev('sgnittes.dom.egapetis');
    }
    return Engine_Api::_()->getApi('settings', 'core')->getSetting($arrayName, null);
  }

  public function isModulesActivated() {
    $pageModArray = array(
        'sitepagealbum' => 'Directory / Pages - Albums Extension',
        'sitepagebadge' => 'Directory / Pages - Badges Extension',
        'sitepagedocument' => 'Directory / Pages - Documents Extension',
        'sitepageevent' => 'Directory / Pages - Events Extension',
        'sitepageform' => 'Directory / Pages - Form Extension',
        'sitepageinvite' => 'Directory / Pages - Inviter Extension',
        'sitepagenote' => 'Directory / Pages - Notes Extension',
        'sitepageoffer' => 'Directory / Pages - Offers Extension',
        'sitepagepoll' => 'Directory / Pages - Polls Extension',
        'sitepagereview' => 'Directory / Pages - Reviews and Ratings Extension',
        'sitepagevideo' => 'Directory / Pages - Videos Extension',
        'sitepagemusic' => 'Directory / Pages - Music Extension',
        'sitepagelikebox' => 'Directory/Pages - Like Box',
				'communityad'	=>	'Advertisements / Community Ads Plugin',
    );
    $notActivatedModArray = array();
    foreach ($pageModArray as $modNameKey => $modNameValue) {
      $isModuleEnabled = Engine_Api::_()->getDbtable('modules', 'core')->isModuleEnabled($modNameKey);
			if( $modNameKey == 'communityad' ) {
				$isModuleActivate = Engine_Api::_()->getApi('settings', 'core')->getSetting('communityad.navi.auth', null);
			}else {
			$isModuleActivate = Engine_Api::_()->getApi('settings', 'core')->getSetting($modNameKey . '.isActivate', null);
			}
      //Condition: If Plugin enabled but not activated.
      if (!empty($isModuleEnabled) && empty($isModuleActivate)) {
        $notActivatedModArray[$modNameKey] = $modNameValue;
      }
    }
    return $notActivatedModArray;
  }

  public function isEnabled() {
    $hostType = Engine_Api::_()->getApi('settings', 'core')->getSetting('sitepage.viewpage.sett', 0);
    $hostName = convert_uudecode($hostType);
    if ($hostName == 'localhost' || strpos($hostName, '192.168.') == false || strpos($hostName, '127.0.') == false) {
      return;
    }

    return 1;
  }

  public function isPluginActivate($modName) {
    return (bool) Engine_Api::_()->getApi('settings', 'core')->getSetting($modName . '.isActivate', 0);
  }

  /**
   *  CHECK Payment PLUGIN ENABLE / DISABLE
   * */
  public function enablePaymentPlugin() {
    return Engine_Api::_()->getDbtable('modules', 'core')->isModuleEnabled('payment');
  }

  /**
   *  Check Viewer able to edit style
   * */
  public function allowStyle() {
    $viewer = Engine_Api::_()->user()->getViewer();
    $viewer_id = $viewer->getIdentity();
    if (!empty($viewer_id)) {
      return (bool) Engine_Api::_()->getDbtable('permissions', 'authorization')->getAllowed('sitepage_page', $viewer->level_id, 'style');
    } else {
      return (bool) 0;
    }
  }

  /**
   * get viewer like pages
   */
  public function getMyLikePages($params=array()) {
    $likeTable = Engine_Api::_()->getDbtable('likes', 'core');
    $likeName = $likeTable->info('name');
    $select = $likeTable->select()
                    ->where($likeName . '.poster_id = ?', $params['poster_id'])
                    ->where($likeName . '.poster_type = ?', $params['poster_type'])
                    ->where($likeName . '.resource_type = ?', $params['resource_type'])
                    ->order($likeName . '.creation_date DESC');
    return $likeTable->fetchAll($select);
  }

  /**
   * Gets feed for which viewer like
   *
   * @$user User_Model_User
   * @param array $params
   */
  public function getFeedActionLikedPages(User_Model_User $user, array $params = array()) {
    $ids = array();
    if (!(bool) Engine_Api::_()->getApi('settings', 'core')->getSetting('sitepage.feed.likepage', 0))
      return $ids;
    $getMyLikes = $this->getMyLikePages(array("poster_type" => $user->getType(), "poster_id" => $user->getIdentity(), "resource_type" => "sitepage_page"));
    $count = count($getMyLikes);

    if (!empty($count)) {
      $resource_ids = array();
      foreach ($getMyLikes as $likeItems) {
        $resource_ids[] = $likeItems->resource_id;
      }

      if (!empty($resource_ids)) {
        //Proc args
        extract($params); //action_id, limit, min_id, max_id
        $actionDbTable = Engine_Api::_()->getDbtable('actions', 'activity');
        $typesAdmin = array("sitepage_post_self", "sitepagealbum_admin_photo_new", "sitepagevideo_admin_new", "sitepageevent_admin_new", "sitepagenote_admin_new", "sitepagepoll_admin_new", "sitepagedocument_admin_new", "sitepageoffer_admin_new", "sitepage_admin_topic_create", "sitepagemusic_admin_new", "sitepage_profile_photo_update");
        $select = $actionDbTable->select()
                        ->where("type in (?)", new Zend_Db_Expr("'" . join("', '", $typesAdmin) . "'"))
                        ->where("subject_type = ? ", "sitepage_page")
                        ->where("subject_id IN(?)", new Zend_Db_Expr(join(',', $resource_ids)))
                        ->order('action_id DESC')
                        ->limit($limit);

        if (null !== $action_id) {
          $select->where('action_id = ?', $action_id);
        } else {
          if (null !== $min_id) {
            $select->where('action_id >= ?', $min_id);
          } else if (null !== $max_id) {
            $select->where('action_id <= ?', $max_id);
          }
        }
        $results = $actionDbTable->fetchAll($select);
        foreach ($results as $actionData)
          $ids[] = $actionData->action_id;
      }
    }
    return $ids;
  }

  /**
   * Gets feed type page title and photo is enable
   *
   * @return bool
   */
  public function isFeedTypePageEnable() {
    return (bool) Engine_Api::_()->getApi('settings', 'core')->getSetting('sitepage.feed.type', 0);
  }

  /**
   * Set default widget in core pages table
   *
   * @param object $table
   * @param string $tablename
   * @param int $page_id
   * @param string $type
   * @param string $widgetname
   * @param int $middle_id 
   * @param int $order 
   * @param string $title 
   * @param int $titlecount    
   */
  function setDefaultDataWidget($table, $tablename, $page_id, $type, $widgetname, $middle_id, $order, $title = null, $titlecount = null) {

    $selectWidgetId = $table->select()
                    ->where('page_id =?', $page_id)
                    ->where('type = ?', $type)
                    ->where('name = ?', $widgetname)
                    ->where('parent_content_id = ?', $middle_id)
                    ->limit(1);
    $fetchWidgetContentId = $selectWidgetId->query()->fetchAll();
    if (empty($fetchWidgetContentId)) {
      $contentWidget = $table->createRow();
      $contentWidget->page_id = $page_id;
      $contentWidget->type = $type;
      $contentWidget->name = $widgetname;
      $contentWidget->parent_content_id = $middle_id;
      $contentWidget->order = $order;
      $contentWidget->params = "{\"title\":\"$title\", \"titleCount\":\"$titlecount\"}";
      $contentWidget->save();
    }
  }

  /**
   * Return page paginator
   *
   * @param int $total_items
   * @param int $items_per_page
   * @param int $p
   * @return paginator
   */
  public function makePage($total_items, $items_per_page, $p) {
    if (!$items_per_page)
      $items_per_page = 1;
    $maxpage = ceil($total_items / $items_per_page);
    if ($maxpage <= 0)
      $maxpage = 1;
    $p = ( ($p > $maxpage) ? $maxpage : ( ($p < 1) ? 1 : $p ) );
    $start = ($p - 1) * $items_per_page;
    return array($start, $p, $maxpage);
  }

  /**
   * Return count
   *
   * @param string $tablename
   * @param string $modulename
   * @param int $page_id
   * @param int $title_count
   * @return paginator
   */
  public function getTotalCount($tablename, $modulename, $page_id, $title_count) {
    $table = Engine_Api::_()->getDbtable($tablename, $modulename);
    $count = 0;
    $count = $table
                    ->select()
                    ->from($table->info('name'), array('count(*) as count'))
                    ->where("page_id = ?", $page_id)
                    ->query()
                    ->fetchColumn();

    return $count;
  }

  /**
   * Return tabid
   *
   * @param string $widgetname
   * @param int $page_id
   * @param int $layout
   * @return tabid
   */
  public function GetTabIdinfo($widgetname, $pageid, $layout) {

    global $sitepage_GetTabIdType;
    $tab_id = '';
    if (!$layout) {
      $tablecontent = Engine_Api::_()->getDbtable('content', 'core');
      $select = $tablecontent->select()
                      ->where('name = ?', $widgetname)
                      ->limit(1);
      $row = $tablecontent->fetchRow($select);
      if ($row !== null) {
        $tab_id = $row->content_id;
      }
    } else {
      $table = Engine_Api::_()->getDbtable('contentpages', 'sitepage');
      $select = $table->select()
                      ->where('name = ?', 'sitepage_index_view')
                      ->where('page_id = ?', $pageid)
                      ->limit(1);
      $row = $table->fetchRow($select);
      if ($row !== null) {
        $page_id = $row->contentpage_id;
      }
      $tablecontent = Engine_Api::_()->getDbtable('content', 'sitepage');
      $select = $tablecontent->select()
                      ->where('name = ?', $widgetname)
                      ->where('contentpage_id = ?', $page_id)
                      ->limit(1);
      $row = $tablecontent->fetchRow($select);
      if ($row !== null) {
        $tab_id = $row->content_id;
      }
    }

    return $sitepage_GetTabIdType ? $tab_id : $sitepage_GetTabIdType;
  }

  /**
   * Gets widgetized page
   *
   * @return Zend_Db_Table_Select
   */
  public function getWidgetizedPage() {

    //GET CORE PAGE TABLE
    $tableNamePage = Engine_Api::_()->getDbtable('pages', 'core');
    $select = $tableNamePage->select()
                    ->from($tableNamePage->info('name'), array('page_id'))
                    ->where('name =?', 'sitepage_index_view')
                    ->limit(1);

    return $tableNamePage->fetchRow($select);
  }

  /**
   * Return parse string
   *
   * @param string $content
   * @return parse string
   */
  public function parseString($content) {
    return str_replace("'", "\'", trim($content));
  }

  /**
   * Return option of showing the widget of third type layout
   *
   * @param int $page_id
   * @param int $layout
   * @return third type layout show or not
   */
  public function getwidget($layout, $page_id) {
    if (!$layout) {
      $page_id = $this->getWidgetizedPage()->page_id;
      if (!empty($page_id)) {
        $table = Engine_Api::_()->getDbtable('content', 'core');
        $selectContent = $table->select()
                        ->from($table->info('name'), 'page_id')
                        ->where("name IN ('core.container-tabs', 'sitepage.widgetlinks-sitepage')")
                        ->where('page_id =?', $page_id)
                        ->limit(1);
        $contentinfo = $selectContent->query()->fetchAll();
        if (empty($contentinfo)) {
          $contentinformation = 0;
        } else {
          $contentinformation = 1;
        }
      }
    } else {
      $table = Engine_Api::_()->getDbtable('contentpages', 'sitepage');
      $select = $table->select()
                      ->from($table->info('name'), 'contentpage_id')
                      ->where('name = ?', 'sitepage_index_view')
                      ->where('page_id = ?', $page_id)
                      ->limit(1);
      $row = $table->fetchRow($select);
      if ($row !== null) {
        $page_id = $row->contentpage_id;
      }

      if (!empty($page_id)) {
        $table = Engine_Api::_()->getDbtable('content', 'sitepage');
        $selectContent = $table->select()
                        ->from($table->info('name'), 'contentpage_id')
                        ->where("name IN ('core.container-tabs', 'sitepage.widgetlinks-sitepage')")
                        ->where('contentpage_id =?', $page_id);
        $contentinfo = $selectContent->query()->fetchAll();
        if (!empty($contentinfo)) {
          $contentinformation = 1;
        } else {
          $contentinformation = 0;
        }
      }
    }
    return $contentinformation;
  }

  /**
   * Return option of showing the top title for widgets
   *
   * @param int $pages_id
   * @param int $layout
   * @return top title show or not
   */
  public function showtoptitle($layout, $pages_id) {
    if (!$layout) {
      $page_id = $this->getWidgetizedPage()->page_id;
      if (!empty($page_id)) {
        $table = Engine_Api::_()->getDbtable('content', 'core');
        $tablename = $table->info('name');
        $selectContent = $table->select()
                        ->from($table->info('name'), 'page_id')
                        ->where('name =?', 'core.container-tabs')
                        ->where('page_id =?', $page_id)
                        ->limit(1);
        $contentinfo = $selectContent->query()->fetchAll();
        if (empty($contentinfo)) {
          $contentinformation = 1;
        } else {
          $contentinformation = 0;
        }
      }
    } else {
      $table = Engine_Api::_()->getDbtable('contentpages', 'sitepage');
      $select = $table->select()
                      ->from($table->info('name'), 'contentpage_id')
                      ->where('name = ?', 'sitepage_index_view')
                      ->where('page_id =?', $pages_id)
                      ->limit(1);
      $row = $table->fetchRow($select);
      if ($row !== null) {
        $page_id = $row->contentpage_id;
      }

      if (!empty($page_id)) {
        $table = Engine_Api::_()->getDbtable('content', 'sitepage');
        $selectContent = $table->select()
                        ->from($table->info('name'), 'contentpage_id')
                        ->where('name =?', 'core.container-tabs')
                        ->where('contentpage_id =?', $page_id)
                        ->limit(1);
        $contentinfo = $selectContent->query()->fetchAll();
        if (empty($contentinfo)) {
          $contentinformation = 1;
        } else {
          $contentinformation = 0;
        }
      }
    }

    return $contentinformation;
  }

  /**
   * Return true or false for ad show on paid pages
   *
   * @param object $sitepage
   * @return true or false
   */
  public function showAdWithPackage($sitepage) {
    if (!Engine_Api::_()->getDbtable('modules', 'core')->isModuleEnabled('communityad')) {
      return 0;
    }

    $package = $sitepage->getPackage();
    if (isset($package->ads)) {
      return (bool) $package->ads;
    } else {
      if (Engine_Api::_()->getApi('settings', 'core')->getSetting('sitepage.communityads', 1)) {
        return (bool) Engine_Api::_()->getApi('settings', 'core')->getSetting('sitepage.adwithpackage', 1);
      } else {
        return 0;
      }
    }
  }

  public function getModulelabel($title) {

    $menuitemsTable = Engine_Api::_()->getDbtable('menuItems', 'core');
    $selectMenuitemsTable = $menuitemsTable->select()->where('name =?', "core_admin_main_plugins_$title");
    $resultMenuitems = $menuitemsTable->fetchRow($selectMenuitemsTable);
    return $resultMenuitems;
  }

}
?>